package com.campuscrowdsourcing.server.controller;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campuscrowdsourcing.server.annotation.Log;
import com.campuscrowdsourcing.server.annotation.LoginCheck;
import com.campuscrowdsourcing.server.common.enums.Action;
import com.campuscrowdsourcing.server.domain.entity.TeamMember;
import com.campuscrowdsourcing.server.domain.model.AjaxResult;
import com.campuscrowdsourcing.server.service.TeamMemberService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 团队成员	表示：XX用户在XX团队，权限为XXX，积分为XX	如果用户名或者团队被删除，该信息直接删除，若该权限被删除，该信息用户权限设置为空	任何外键信息更新时，该信息随之更新 前端控制器
 * </p>
 *
 * @author Xinyuan Zhao
 * @since 2023-03-15
 */
@RestController
@RequestMapping("/api/teamMember")
public class TeamMemberController {
    @Resource
    private TeamMemberService teamMemberService;

    @PostMapping
    @Log(title = "新增团队成员", action = Action.INSERT)
    public AjaxResult saveTeamMember(@RequestBody TeamMember teamMember) {
        if (teamMember.getTeamRoleId() == 1){
            return AjaxResult.fail("团队创建者不可改变");
        }
        teamMemberService.save(teamMember);
        return AjaxResult.success();
    }

    @PutMapping
    @Log(title = "编辑团队成员", action = Action.UPDATE)
    @LoginCheck
    public AjaxResult updateTeamMember(@RequestBody TeamMember teamMember) {
        if (teamMember.getTeamRoleId() == 1){
            return AjaxResult.fail("团队创建者不可改变");
        }
        TeamMember teammember1 = teamMemberService.getById(teamMember.getId());
        if (teammember1.getTeamRoleId() == 1){
            return AjaxResult.fail("团队创建者不可改变");
        }
        teamMemberService.updateById(teamMember);
        return AjaxResult.success();
    }

    @DeleteMapping("/{id}")
    @Log(title = "删除团队成员", action = Action.DELETE)
    public AjaxResult deleteTeamMember(@PathVariable Integer id) {
        TeamMember teammember = teamMemberService.getById(id);
        if(teammember.getTeamRoleId() == 1)
        {
            return AjaxResult.fail("团队创建者不可被删除，请直接删除该团队");
        }
        teamMemberService.removeById(id);
        return AjaxResult.success();
    }

    @PostMapping("/del/batch")
    @Log(title = "批量删除团队成员", action = Action.DELETE)
    public AjaxResult deleteBatchTeamMember(@RequestBody List<Integer> ids) {
        teamMemberService.removeByIds(ids);
        return AjaxResult.success();
    }

    @GetMapping
    @Log(title = "查看团队成员信息", action = Action.SELECT)
    public AjaxResult listTeamMember() {
        return AjaxResult.success(teamMemberService.list());
    }

    @GetMapping("/{id}")
    @Log(title = "id查找团队成员信息", action = Action.SELECT)
    public AjaxResult getTeamMemberById(@PathVariable Integer id) {
        TeamMember teamMember = teamMemberService.getById(id);
        if(teamMember == null)
        {
            return AjaxResult.fail("该信息不存在或已删除");
        }
        return AjaxResult.success(teamMember);
    }

    @GetMapping("/page")
    @Log(title = "团队成员信息分页查询", action = Action.SELECT)
    public AjaxResult listTeamMemberPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<TeamMember> queryWrapper = new QueryWrapper<TeamMember>().orderByDesc("id");
        queryWrapper.like(!"".equals(name), "name", name);
        return AjaxResult.success(teamMemberService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    @Log(title = "团队成员信息导出", action = Action.SELECT)
    public void exportTeamMember(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<TeamMember> list = teamMemberService.list();
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("Teammember信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }
}

